package com.afc.struts.test.data;

import java.text.ParseException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.afc.struts.test.model.Person;
import com.afc.struts.test.model.Person.DefaultPerson;
import com.afc.struts.utils.DateUtils;

public class PersonDao
{
  private PersonDao()
  {
    try
    {
      Person dara = new DefaultPerson("Dara", "Tran", null, null, null);
      create(dara);
      create(new DefaultPerson("Romain", "Gallan", 1.86, DateUtils.parse("04/04/1977"), dara));
      create(new DefaultPerson("Ollivier", "Guignard", null, null, null));
    }
    catch (ParseException anException)
    {
      throw new RuntimeException("Unable to create PersonDao", anException);
    }
  }

  public Collection<Person> retrieveAll()
  {
    return personsById.values();
  }

  public Person retrieve(int anId)
  {
    return personsById.get(anId);
  }

  public void create(Person aPerson)
  {
    int id = ++keySequence;
    personsById.put(id, aPerson);
    aPerson.setId(id);
  }

  public void update(Person aPerson)
  {
    personsById.put(aPerson.getId(), aPerson);
  }

  public void delete(int anId)
  {
    personsById.remove(anId);
  }

  protected int keySequence;
  protected Map<Integer, Person> personsById = new HashMap<>();

  static public PersonDao getInstance()
  {
    return INSTANCE;
  }

  static private final PersonDao INSTANCE = new PersonDao();
}
